<?php

namespace App\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\UserResource;
use App\Models\Information;
use App\Models\User;
use Auth;
use DB;
use Illuminate\Http\Request;

class UserController extends Controller
{
    public function info()
    {
        return Auth::user();
    }

    public function index()
    {
        $users = UserResource::collection(User::with('information')->where('member', false)->get());
        return $users;
    }

    //普通会员
    public function normal()
    {

        $users = UserResource::collection(User::where('member', false)->get());
        return $users;
    }

    //联盟会员
    public function member()
    {
        $users = UserResource::collection(User::with('information')->where('member', true)->get());
        return $users;
    }

    /**
     * 拥有角色的用户
     */
    public function hasroleable()
    {
        $users = User::with('roles')->get();
        return $users;
    }

    public function show(User $user)
    {
        return $user;
    }


    public function update(Request $request, User $user)
    {
        $user->update($request->input());

//判断有没有approve，如果有就在information中添加
        if (isset($request->approve['merchant_name'])) {
            $information = $request->approve + ['user_id' => $user->id];

            $user->information()->updateOrCreate(['user_id' => $user->id], $information);
            return $this->message('用户修改成功，商户资料已同步');

        }
        return $this->message('用户修改成功，商户资料待完善');
    }


    public function getApprove()
    {
        //审批中不为空
        return User::where('approve', '!=', null)->where('member', false)->get();
    }

    //直接注册联盟会员
    public function store(Request $request)
    {
        $request->validate(['name' => 'required', 'member' => 'required', 'mobile' => ['required', 'numeric', 'regex:/1\d{10}/']], [
            'member.required' => '商户类型不能为空'
        ]);
        if ($request->input('member') == true) {
            DB::transaction(function () use ($request) {
                $user = User::create($request->except('member'));//因为需要提交审批，member忽略

                $information = $request->approve + ['user_id' => $user->id];

                $user->information()->save(new Information($information));
            });
            DB::commit();
        } else {
            $user = User::create($request->except('member'));
        }

        return $this->message('保存成功');
    }

    //同意审批，用户为联盟商户
    public function agree(Request $request, User $user)
    {
        $user->member = 1;
        $user->save();
        return $this->message('提交成功');
    }

    //拒绝审批，用户任然为普通商户

    public function reject(Request $request, User $user)
    {
        $user->member = false;
        $user->save();
        return $this->message('审批拒绝');
    }


    public function destroy(User $user)
    {
        $user->delete();
        return $this->message('删除成功');
    }

    /**
     * 设置为管理员
     * @param Request $request
     * @param User $user
     * @return array
     */
    public function setAdmin(Request $request, User $user)
    {
        $user->update(['is_admin' => true]);
        return $this->message('管理员设置成功，请为其赋予角色');
    }

    /**
     * 取消管理员
     * @param Request $request
     * @param User $user
     * @return array
     */
    public function cancelAdmin(Request $request, User $user)
    {

        $user->update(['is_admin' => false]);
        $user->roles->map(function ($role) use ($user) {
            $user->removeRole($role['name']);
        });
        return $this->message('已取消管理员，其角色及权限已回收');
    }

    /**
     * 管理员列表
     * @return mixed
     */
    public function isAdmin()
    {
        $users = User::where('is_admin', true)->with('roles')->get();
        return $users;
    }

    /**
     * 找回密码
     * @param Request $request
     * @param User $user
     * @return array
     */
    public function forget(Request $request, User $user)
    {
        $request->validate([
            'account' => ['required', new AccountRule(request('account')), Rule::exists('users', UserService::account())],
            'password' => ['required', 'confirmed', 'between:5,20'],
            'code' => ['sometimes', 'required', new CodeRule(request('account'))]
        ], [
            'account.required' => '帐号不能为空',
            'account.exists' => '帐号不存在',
            'password.required' => '密码不能为空',
            'code.required' => '验证码不能为空'
        ]);

        $user = User::where(UserService::account(), $request->account)->first();
        $user->password = Hash::make($request->password);
        $user->save();
        return ['message' => '密码重置成功', 'token' => $this->token($user)];
    }
}
